<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 页面已完成
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.status"
          placeholder="状态"
          class="handle-select mr10"
        >
          <el-option key="1" label="发送成功" value="1"></el-option>
          <el-option key="0" label="发送失败" value="0"></el-option>
        </el-select>
        <el-input
          v-model="query.mobile"
          clearable
          placeholder="手机号"
          class="handle-input mr10"
          @keyup.native.enter="handleSearch()"
        ></el-input>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="primary"
          @click="getMessageConfig"
          v-if="msPermissions.includes('sys:sms:update')"
          >短信配置</el-button
        >
        <el-button
          type="primary"
          @click="sendInfo"
          v-if="msPermissions.includes('sys:sms:save')"
          >发送短信</el-button
        >
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="msPermissions.includes('sys:sms:delete')"
          >删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'createDate', order: 'descending' }"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="platform"
          label="平台类型"
          sortable
          align="center"
        ></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>

        <el-table-column prop="params1" label="参数1"></el-table-column>
        <el-table-column prop="params2" label="参数2"></el-table-column>
        <el-table-column prop="params3" label="参数3"></el-table-column>
        <el-table-column prop="params4" label="参数4"></el-table-column>
        <el-table-column label="状态" prop="status" align="center" sortable>
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.status === '发送成功'
                  ? 'success'
                  : scope.row.status === '发送失败'
                  ? 'danger'
                  : ''
              "
              >{{ scope.row.status }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="createDate"
          label="发送时间"
          sortable
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="msPermissions.includes('sys:sms:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="msPermissions.includes('sys:sms:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form :rules="rules" :model="editRuleForm" label-width="70px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editRuleForm.mobile" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="editRuleForm.status" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /编辑弹出框 -->

    <!-- 信息配置弹出框 -->
    <el-dialog title="短信配置" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" :rules="rules">
        <el-form-item
          label="平台类型"
          prop="platform"
          :label-width="formLabelWidth"
        >
          <el-radio-group v-model="ruleForm.platform" @change="handlePlatform">
            <el-radio v-model="ruleForm.platform" label="1"> 阿里云</el-radio>
            <el-radio v-model="ruleForm.platform" label="2">腾讯云</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 阿里云 -->
        <el-form-item
          v-if="ruleForm.platform == '1'"
          label="Key"
          prop="aliyunAccessKeyId"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.aliyunAccessKeyId"
            autocomplete="off"
            placeholder="阿里云AccessKeyId"
            clearable
          ></el-input>
        </el-form-item>
        <!-- 腾讯云 -->
        <el-form-item
          v-else
          label="AppId"
          prop="qcloudAppId"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.qcloudAppId"
            autocomplete="off"
            placeholder="腾讯云AppId"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="ruleForm.platform == '1'"
          label="Secret"
          prop="aliyunAccessKeySecret"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.aliyunAccessKeySecret"
            autocomplete="off"
            placeholder="阿里云AccessKeySecret"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          v-else
          label="AppKey"
          prop="qcloudAppKey"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.qcloudAppKey"
            autocomplete="off"
            placeholder="腾讯云AppKey"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="ruleForm.platform == '1'"
          label="短信签名"
          prop="aliyunSignName"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.aliyunSignName"
            autocomplete="off"
            placeholder="短信签名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          v-else
          label="短信签名"
          prop="qcloudSignName"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.qcloudSignName"
            autocomplete="off"
            placeholder="短信签名"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="ruleForm.platform == '1'"
          label="短信模版"
          prop="aliyunTemplateCode"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.aliyunTemplateCode"
            autocomplete="off"
            placeholder="短信模版CODE"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          v-else
          label="短信模版"
          prop="qcloudTemplateId"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="ruleForm.qcloudTemplateId"
            autocomplete="off"
            placeholder="短信模版ID"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveConfig">确 定</el-button>
      </div>
    </el-dialog>
    <!-- /信息配置弹出框 -->

    <!-- 发送短信弹出框 -->
    <el-dialog title="发送短信" :visible.sync="sendInfoVisible" width="30%">
      <el-form :rules="rules" :model="sendInfoRuleForm" label-width="70px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="sendInfoRuleForm.mobile" clearable></el-input>
        </el-form-item>
        <el-form-item label="参数" prop="params">
          <el-input
            v-model="sendInfoRuleForm.params"
            placeholder='如: {"code": "123456"}'
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sendInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSendInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /发送短信弹出框 -->
  </div>
</template>

<script>
// import { messageMangeMixin } from "common/js/messageManage";
import util from "utils/util";
import qs from "qs";
import { mapGetters } from "vuex";
export default {
  name: "messagesms",
  // mixins: [messageMangeMixin],
  data() {
    return {
      msPermissions: [],
      // 发送短信弹出框
      sendInfoVisible: false,
      sendInfoRuleForm: { mobile: "", status: "", params: "" },
      // 信息配置弹出框, 9字段固定不要动
      ruleForm: {
        platform: "",
        aliyunAccessKeyId: "",
        aliyunAccessKeySecret: "",
        aliyunSignName: "",
        aliyunTemplateCode: "",
        qcloudAppId: "",
        qcloudAppKey: "",
        qcloudSignName: "",
        qcloudTemplateId: "",
      },
      editRuleForm: {
        mobile: "",
        status: "",
      },
      rules: {
        mobile: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        status: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        aliyunAccessKeyId: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        aliyunAccessKeySecret: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        aliyunSignName: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        aliyunTemplateCode: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        qcloudAppId: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        qcloudAppKey: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        qcloudSignName: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        qcloudTemplateId: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
      },
      dialogFormVisible: false,
      formLabelWidth: "120px",
      // 搜索相关
      query: {
        order: "",
        orderField: "",
        pageIndex: 1,
        pageSize: 20,
        status: "",
        mobile: "",
      },
      tableData: [
        {
          id: "",
          platform: "",
          mobile: "",
          params1: "",
          params2: "",
          params3: "",
          params4: "",
          createDate: "2019-10-11",
          status: "成功",
        },
      ],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      ids: [],
    };
  },
  methods: {
    // 获取数据
    getMessageSmsData({
      order = this.query.order,
      orderField = this.query.orderField,
      page = this.query.pageIndex,
      limit = this.query.pageSize,
      mobile = this.query.mobile,
      _t = Date.now(),
      status = this.query.status,
    }) {
      this.$axios
        .get("/sys/sms/page", {
          params: {
            order,
            orderField,
            page,
            limit,
            mobile,
            _t,
            status,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          // console.log(res); // 接口数据可能需要过滤属性
          // 数据尚未渲染
          this.tableData = res.data.list;
          this.tableData.map((item) => {
            item.platform = item.platform == 1 ? "阿里云" : "腾讯云";
            item.status = item.status == 1 ? "发送成功" : "发送失败";
          });
          this.pageTotal = res.data.total || 0;
        })
        .catch(() => {});
    },
    // 表头排序
    sortChange({ column, prop, order }) {
      // console.log(column, prop, order);
      prop = prop === "createDate" ? "create_date" : prop;
      this.$set(this.query, "orderField", prop);
      if (order === "ascending") {
        this.$set(this.query, "order", order.substr(0, 3));
        this.getMessageSmsData({});
      } else if (order === "descending") {
        this.$set(this.query, "order", order.substr(0, 4));
        this.getMessageSmsData({});
      }
    },
    // 发送短信
    sendInfo() {
      this.sendInfoVisible = true;
    },
    saveSendInfo() {
      this.sendInfoVisible = false;
      this.$axios
        .post(
          "/sys/sms/send",
          qs.stringify({
            mobile: this.sendInfoRuleForm.mobile,
            params: JSON.stringify({ code: this.sendInfoRuleForm.params }),
          }),
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          }
        )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.getMessageSmsData({});
          this.$message.success(res.msg);
        })
        .catch(() => {});
    },
    // 信息配置
    getMessageConfig() {
      this.dialogFormVisible = true;
      this.$axios
        .get("/sys/sms/config", {
          params: {
            _t: Date.now(),
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.ruleForm = res.data;
          this.ruleForm["platform"] = this.ruleForm["platform"].toString();
        })
        .catch(() => {});
    },

    // 单选云平台
    handlePlatform(value) {
      // 1 => 阿里 2 => 腾讯
      // console.log(value);
      this.ruleForm.platform = value;
    },
    // 短信配置提交
    saveConfig() {
      this.dialogFormVisible = false;
      this.$axios
        .post("/sys/sms/saveConfig", {
          ...this.ruleForm,
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return;
          }
          // console.log(res);
          this.$message.success("操作成功");
        })
        .catch(() => {});
    },

    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      var params = {
        order: this.query.order,
        orderField: this.query.orderField,
        page: this.query.pageIndex,
        limit: this.query.pageSize,
        mobile: this.query.mobile,
        status: this.query.status,
        _t: Date.now(),
      };
      this.tableData = [];
      this.getMessageSmsData(params);
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(
        this,
        "/sys/sms",
        index,
        this.ids,
        this.getMessageSmsData
      );
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      util.delete.call(this, "/sys/sms", "", ids, this.getMessageSmsData);
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.form = row;
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      this.editVisible = false;
      this.$message.success(`修改第 ${this.idx + 1} 行成功`);
      this.$set(this.tableData, this.idx, this.form);
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getMessageSmsData({});
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getMessageSmsData({});
    },
  },
  created() {
    this.getMessageSmsData({});
    this.msPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/message-sms") {
        this.msPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.msPermissions = newVal;
    },
  },
};
</script>

<style scoped>
@import url("../../common/css/index.css");
</style>
